package top.mcwebsite.lib.gradle.plugin.transform

import com.android.build.api.artifact.ScopedArtifact
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import com.android.build.api.variant.ScopedArtifacts
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.configurationcache.extensions.capitalized
import top.mcwebsite.lib.gradle.plugin.transform.ServiceLoader.Companion.newServiceLoader
import top.mcwebsite.lib.transform.api.Transformer

class TransformPlugin : Plugin<Project> {
    override fun apply(project: Project) {
        val isLibrary = project.plugins.any { it.javaClass.name.contains("LibraryPlugin") }
        if (isLibrary) {
            throw IllegalStateException("Transform Plugin must be used in Application module")
        }
        project.extensions.configure(ApplicationAndroidComponentsExtension::class.java) {
            onVariants { variant ->
                val transformTask = project.tasks.register(
                    "transformClass${variant.name.capitalized()}",
                    TransformTask::class.java
                ) {
                    transformers = project.buildscript.classLoader.newServiceLoader<Transformer>().load()
                }
                variant.artifacts
                    .forScope(ScopedArtifacts.Scope.ALL)
                    .use(transformTask)
                    .toTransform(
                        ScopedArtifact.CLASSES,
                        TransformTask::allJars,
                        TransformTask::allDirectories,
                        TransformTask::outputJar
                    )
            }
        }
    }
}